package cn.iocoder.yudao.module.shop.service.crossorder;

import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.shop.dal.dataobject.order.ShopOrderDO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.tenantdetail.TenantDetailDO;
import cn.iocoder.yudao.module.system.service.tenantdetail.TenantDetailService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.*;
import cn.iocoder.yudao.module.shop.controller.admin.crossorder.vo.*;
import cn.iocoder.yudao.module.shop.dal.dataobject.crossorder.ShopCrossOrderDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.shop.convert.crossorder.ShopCrossOrderConvert;
import cn.iocoder.yudao.module.shop.dal.mysql.crossorder.ShopCrossOrderMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.shop.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 跨店铺 Service 实现类
 *
 * @author 曹建伟
 */
@Service
@Validated
public class ShopCrossOrderServiceImpl implements ShopCrossOrderService {

    @Resource
    private ShopCrossOrderMapper crossOrderMapper;

    @Resource
    private MemberUserApi memberUserApi;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private TenantDetailService tenantDetailService;

    @Override
    public Long createCrossOrder(ShopCrossOrderCreateReqVO createReqVO) {
        // 插入
        ShopCrossOrderDO crossOrder = ShopCrossOrderConvert.INSTANCE.convert(createReqVO);
        crossOrderMapper.insert(crossOrder);
        // 返回
        return crossOrder.getId();
    }

    @Override
    public void updateCrossOrder(ShopCrossOrderUpdateReqVO updateReqVO) {
        // 校验存在
        validateCrossOrderExists(updateReqVO.getId());
        // 更新
        ShopCrossOrderDO updateObj = ShopCrossOrderConvert.INSTANCE.convert(updateReqVO);
        crossOrderMapper.updateById(updateObj);
    }

    @Override
    public void deleteCrossOrder(Long id) {
        // 校验存在
        validateCrossOrderExists(id);
        // 删除
        crossOrderMapper.deleteById(id);
    }

    private void validateCrossOrderExists(Long id) {
        if (crossOrderMapper.selectById(id) == null) {
            throw exception(CROSS_ORDER_NOT_EXISTS);
        }
    }

    @Override
    public ShopCrossOrderDO getCrossOrder(Long id) {
        return crossOrderMapper.selectById(id);
    }

    @Override
    public List<ShopCrossOrderDO> getCrossOrderList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return crossOrderMapper.selectBatchIds(ids);
    }

    @Override
    public List<ShopCrossOrderDO> getSourceCrossOrderListByTenantId(Long tenantId, LocalDateTime startTime, LocalDateTime endTime){
        return crossOrderMapper.selectListSourceByTenantId(tenantId, startTime, endTime);
    }

    @Override
    public List<ShopCrossOrderDO> getTargetCrossOrderListByTenantId(Long tenantId, LocalDateTime startTime, LocalDateTime endTime){
        return crossOrderMapper.selectListTargetByTenantId(tenantId, startTime, endTime);
    }

    @Override
    public Boolean confirm(Long tenantId, Long id){
        ShopCrossOrderDO crossOrderDO = crossOrderMapper.selectById(id);

        if (crossOrderDO == null) {
            throw exception(CROSS_ORDER_NOT_EXISTS);
        }

        if(!crossOrderDO.getTargetTenantId().equals(tenantId)){
            throw exception(CROSS_ORDER_CONFIRM_ERROR);
        }

        if(crossOrderDO.getConfirmed()){
            return true;
        }

        crossOrderDO.setConfirmed(true);

        crossOrderMapper.updateById(crossOrderDO);

        return true;
    }

    @Override
    public PageResult<ShopCrossOrderDO> getCrossOrderPage(ShopCrossOrderPageReqVO pageReqVO) {
        return crossOrderMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ShopCrossOrderDO> getCrossOrderList(ShopCrossOrderExportReqVO exportReqVO) {
        return crossOrderMapper.selectList(exportReqVO);
    }

    @Override
    public Boolean rollback(ShopOrderDO order){
        if(!order.getWalletCharge() && !order.getTimesCharge()){
            return true;
        }

        MemberUserRespDTO member = memberUserApi.getUser(order.getMemberId());
        if(member == null){
            throw exception(ORDER_CHECK_NOT_FOUND_MEMBER);
        }

        if(member.getTenantId().equals(order.getTenantId())){
            return true;
        }

        ShopCrossOrderDO crossOrderDO = crossOrderMapper.selectOne(ShopCrossOrderDO::getOrderId, order.getId());
        if(crossOrderDO == null){
            return true;
        }

        crossOrderMapper.deleteById(crossOrderDO);

        return true;
    }

    @Override
    public Boolean checkOrder(ShopOrderDO order){
        if(!order.getWalletCharge() && !order.getTimesCharge()){
            return true;
        }

        MemberUserRespDTO member = memberUserApi.getUser(order.getMemberId());
        if(member == null){
            throw exception(ORDER_CHECK_NOT_FOUND_MEMBER);
        }

        if(member.getTenantId().equals(order.getTenantId())){
            return true;
        }

        AdminUserRespDTO user = adminUserApi.getUser(order.getUserId());
        if(user == null){
            throw exception(ORDER_CHECK_NOT_FOUND_MASTER);
        }

        TenantDetailDO targetTenant = tenantDetailService.getTenantDetailByTenantId(order.getTenantId());
        if(targetTenant == null){
            throw exception(ORDER_CHECK_NOT_FOUND_TARGET_TENANT);
        }

        TenantDetailDO sourceTenant = tenantDetailService.getTenantDetailByTenantId(member.getTenantId());
        if(sourceTenant == null){
            throw exception(ORDER_CHECK_NOT_FOUND_SOURCE_TENANT);
        }

        ShopCrossOrderDO crossOrderDO = new ShopCrossOrderDO();
        crossOrderDO.setMemberId(member.getId());
        crossOrderDO.setMemberName(member.getNickname());
        crossOrderDO.setUserId(order.getUserId());
        crossOrderDO.setUserName(user.getNickname());

        crossOrderDO.setOrderId(order.getId());
        crossOrderDO.setOrderComment(order.getComment());

        crossOrderDO.setSourceTenantId(sourceTenant.getTenantId());
        crossOrderDO.setSourceTenantName(sourceTenant.getName());
        crossOrderDO.setTargetTenantId(targetTenant.getTenantId());
        crossOrderDO.setTargetTenantName(targetTenant.getName());

        crossOrderDO.setOrderTime(order.getStartTime());
        crossOrderDO.setConfirmed(false);
        crossOrderDO.setIsTimesCharge(order.getTimesCharge());
        crossOrderDO.setIsWalletCharge(order.getWalletCharge());

        crossOrderDO.setPayValue(order.getPayPrice());

        crossOrderMapper.insert(crossOrderDO);

        return true;
    }

}
